package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.search.pojo.SkuInfo;
import com.changgou.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public Map search(Map<String, String> paramMap) {
        HashMap<String, Object> resultMap = new HashMap<>();
        //参数不为空才可以进行查询
        if (paramMap != null) {
            //构建查询条件对象
            NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

            //获取关键字进行查询
            if (StringUtils.isNotEmpty(paramMap.get("keywords"))) {
                boolQuery.must(QueryBuilders.matchQuery("name", paramMap.get("keywords")).operator(Operator.AND));
            }
            //按照品牌进行查询
            if (StringUtils.isNotEmpty(paramMap.get("brand"))) {
                boolQuery.filter(QueryBuilders.termQuery("brandName", paramMap.get("brand")));
            }
            //按照规格进行过滤查询
            paramMap.keySet().parallelStream()
                    .filter(key -> key.startsWith("spec_")) // 过滤以"spec_"开头的键
                    .forEach(key -> {
                        String value = paramMap.get(key).replace("%2B", "+"); // 获取值并替换特殊字符
                        String specKey = key.substring(5); // 截取"spec_"后的部分作为specMap中的键
                        boolQuery.filter(QueryBuilders.termQuery("specMap." + specKey + "keyword", value)); // 添加过滤条件到boolQuery
                    });
            //按照价格区间进行过滤查询
            if (StringUtils.isNotEmpty(paramMap.get("price"))) {
                String[] prices = paramMap.get("price").split("-");
                if (prices.length == 2)
                    boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]).lte(prices[1]));
                boolQuery.filter(QueryBuilders.rangeQuery("price").gte(prices[0]));
            }
            queryBuilder.withQuery(boolQuery);

            //对品牌进行聚合
            queryBuilder.addAggregation(AggregationBuilders.terms("skuBrand").field("brandName"));
            //按照规格进行聚合
            queryBuilder.addAggregation(AggregationBuilders.terms("skuSpec").field("spec.keyword"));
            //开始分页查询
            String pageNum = paramMap.get("pageNum");
            String pageSize = paramMap.get("pageSize");
            if (StringUtils.isEmpty(pageNum)) {
                pageNum = "1";
            }
            if (StringUtils.isEmpty(pageSize)) {
                pageSize = "30";
            }
            //设置分页
            queryBuilder.withPageable(PageRequest.of(Integer.parseInt(pageNum) - 1, Integer.parseInt(pageSize)));
            //排序查询
            if (StringUtils.isNotBlank(paramMap.get("sortField")) && StringUtils.isNotBlank(paramMap.get("sortRule"))) {
                if ("ASC".equals(paramMap.get("sortRule"))) {
                    queryBuilder.withSort(SortBuilders.fieldSort(paramMap.get("sortField")).order(SortOrder.ASC));
                } else {
                    queryBuilder.withSort(SortBuilders.fieldSort(paramMap.get("sortField")).order(SortOrder.DESC));
                }
            }
            //设置高亮及样式
            queryBuilder.withHighlightFields(new HighlightBuilder.Field("name").preTags("<span style='color:red'>").postTags("</span>"));
            //开启查询
            /**
             * 1.条件构造对象
             * 2.查询操作实体类
             * 3.查询结果操作对象
             */
            AggregatedPage<SkuInfo> skuInfos = elasticsearchTemplate.queryForPage(queryBuilder.build(), SkuInfo.class, new SearchResultMapper() {
                @Override
                public <T> AggregatedPage<T> mapResults(SearchResponse searchResponse, Class<T> aClass, Pageable pageable) {
                    ArrayList<T> list = new ArrayList<>();
                    //获取查询结果
                    SearchHits hits = searchResponse.getHits();
                    if (hits != null) {
                        for (SearchHit hit : hits) {
                            SkuInfo skuInfo = JSON.parseObject(hit.getSourceAsString(), SkuInfo.class);

                            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                            if (highlightFields != null && highlightFields.size() > 0) {
                                skuInfo.setName(highlightFields.get("name").getFragments()[0].toString());
                            }
                            list.add((T) skuInfo);

                        }
                    }
                    return new AggregatedPageImpl<T>(list, pageable, hits.getTotalHits(), searchResponse.getAggregations());
                }
            });
            //封装返回结果
            resultMap.put("rows", skuInfos.getContent());
            resultMap.put("total", skuInfos.getTotalElements());
            resultMap.put("totalPages", skuInfos.getTotalPages());
            //封装品牌
            StringTerms skuBrand = (StringTerms) skuInfos.getAggregation("skuBrand");
            List<String> brandList = skuBrand.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("brandList", brandList);
            //封装规格分组结果
            StringTerms skuSpec = (StringTerms) skuInfos.getAggregation("skuSpec");
            List<String> specList = skuSpec.getBuckets().stream().map(bucket -> bucket.getKeyAsString()).collect(Collectors.toList());
            resultMap.put("specList", formatSpec(specList));
            //封装当前页
            resultMap.put("pageNum", pageNum);
            return resultMap;
        }
        return null;
    }



    /**
     * 格式化规格列表
     * @param specList 规格列表
     * @return 格式化后的规格Map，键为规格名称，值为对应规格的集合
     */
    public Map<String, Set<String>> formatSpec(List<String> specList) {
        // 检查规格列表是否为空
        if (specList != null && specList.size() > 0) {
            // 将规格列表转换为流，处理每个规格Json字符串
            return specList.stream()
                    // 将每个Json字符串解析为HashMap<String, String>类型
                    .map(specJsonString -> (HashMap<String, String>) JSON.parseObject(specJsonString, Map.class))
                    // 将每个HashMap中的entry扁平化为单个流
                    .flatMap(specMap -> specMap.entrySet().stream())
                    // 根据规格名称进行分组，将具有相同名称的规格值收集到一个Set中
                    .collect(Collectors.groupingBy(HashMap.Entry::getKey,
                            Collectors.mapping(HashMap.Entry::getValue, Collectors.toSet())));
        }
        // 如果规格列表为空，则返回一个空的HashMap
        return new HashMap<>();
    }
}
